import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { FormProps } from 'antd';
import { Button, Form, Input, message } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useDispatch} from 'react-redux'
import style from './login.module.scss'
import { LoginApi } from '@/api/modules/loginApi';
import { setUserInfo } from '@/store/modules/userSlice'
import useDebounce  from '@/hooks/useDebounce'

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
const Login: React.FC = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  // 点击登录按钮,触发这里的onFinish
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    try {
      let res = await LoginApi(values)
      console.log(res,'res')
      if(res.data.status === 1000){
        // 存储token 本地存储
        console.log(res.data.data.token)
        localStorage.setItem('token',JSON.stringify('Bearer ' + res.data.data.token))
        // localStorage.setItem('username',JSON.stringify(res.data.data.username))
        dispatch(setUserInfo(res.data.data.username))
        message.success('登录成功')
        // 跳转到首页
        navigate('/sys/index')
      }
      
    } catch (error) {
      Promise.reject(error)
    }
  };


  return (
      <div className={style.container}>
        <div className={style.title}>
          <h2>通用管理后台</h2>
        </div>
        <div className={style.content}>
          <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          style={{ width: 600 }}
          initialValues={{ remember: true }}
          // 做了防抖处理
          onFinish={useDebounce(onFinish,500)}
          autoComplete="off"
          form={form}
        >
          <Form.Item<FieldType>
            label="账号"
            name="username"
            rules={[{ required: true, message: '请输入账号!' }]}
          >
            <Input prefix={<UserOutlined />} />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>
          <Form.Item label={null}>
            <div style={{width:"100%",display:"flex",justifyContent:"space-evenly"}}>
              <Button type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
              登录
            </Button>
            <Button onClick={()=>form.resetFields()} >
              重置
            </Button>
            </div>
          </Form.Item>
          </Form>
        </div>
        <div style={{color:"#fff"}}>
          测试账号:admin / 密码: 123456
        </div>
      </div>
  )
}

export default Login;
